import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/HomeView.vue'),
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/login/LoginView.vue'),
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('../views/AboutView.vue'),
      meta: { requiresAuth: true, permission: 'dashboard:view' },
    },

    {
      path: '/dashboard',
      name: 'Dashboard',
      component: () => import('../views/login/DashboardView.vue'),
      meta: { requiresAuth: true }, // 添加一个 meta 字段来标记这个路由需要身份验证
    },
    {
      path: '/info',
      name: 'info',
      component: () => import('../views/InfoView.vue'),
      meta: { requiresAuth: false },
    },
    {
      path: '/404',
      name: '404',
      component: () => import('../views/404/FailView.vue'),
      meta: { requiresAuth: false },
    },
  ],
})

// 导航守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = !!localStorage.getItem('authToken') // 假设你通过 localStorage 存储身份验证令牌
  if (to.matched.some((record) => record.meta.requiresAuth) && !isAuthenticated) {
    console.log(isAuthenticated)

    // 如果目标路由需要身份验证且用户未登录，则重定向到登录页面
    next({
      path: '/404', //重定向页面
      query: { redirect: to.fullPath }, // 可选：将当前路由的完整路径作为查询参数传递给登录页面，以便登录后重定向回来
    })
  } else {
    next() // 确保一定要调用 next()
  }
})

export default router
